package org.example.medical.utils;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 检查请求的处理器是否是 HandlerMethod 类型
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 检查方法或类是否有 AuthRequired 注解
            if (handlerMethod.getMethod().isAnnotationPresent(AuthRequired.class) || 
                handlerMethod.getBeanType().isAnnotationPresent(AuthRequired.class)) {
                // 获取 Session
                HttpSession session = request.getSession(false);
                if (session == null || session.getAttribute("user") == null) {
                    // 如果没有登录，返回未授权的响应
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    return false;
                }
            }
        }
        return true;
    }
}